

package com.example.actearly_revised;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.Html;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;

import com.example.actearly_revised.JournalObject.JNode;
import com.example.actearly_revised.QuestionsObject.Node;
import com.example.actearly_revised.R;


public class SummaryPage extends Activity {
	private Button emailButton;
	private TabHomePage parent;
	private static int currentmilestone;
	private static int profile_number;
	private ImageButton leftButton;
	private ImageButton rightButton;
	private TextView currentAge;
	private TextView summaryText;
	private CheckBox EmailDoc;
	
	private int[] ageID;
	private String[] ageGroups;
	private int ageCounter;
	
	// answer table options
	final String yes_ans = "yes";
	final String no_ans = "no";
	final String maybe_ans = "notsure";
	
	private ExpandableListView ExpandList;
	private ArrayList<ExpandListGroup> topLevelGroup;
	private ExpandListAdapter ExpAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_summary_page);
		
		this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		
		leftButton = (ImageButton) findViewById(R.id.leftButton);
		rightButton = (ImageButton) findViewById(R.id.rightButton);
		currentAge= (TextView) findViewById(R.id.currentAge);
		summaryText= (TextView) findViewById(R.id.summaryText);
		
				
		parent = (TabHomePage) this.getParent();
		this.currentmilestone = parent.currentmilestone;
		this.profile_number = parent.profile_number;
		
		
		ageGroups= getResources().getStringArray(R.array.milestoneAges);
		ageID = new int[] {
				2,4,6,9,12,18,24,36,48,60
		};
		ageCounter = IndexOf(this.currentmilestone,ageID);
		currentAge.setText(ageGroups[ageCounter]);
	
		ExpandList = (ExpandableListView) findViewById(R.id.SummaryExpList);
        		
		LinearLayout pageLayout=(LinearLayout)findViewById(R.id.summaryLayout);
		//pageLayout.setBackgroundResource(R.drawable.background);
				
		Typeface customFont = Typeface.createFromAsset(getAssets(), "fonts/futuram.ttf");

		currentAge.setTypeface(customFont);
		summaryText.setTypeface(customFont);
			
		EmailDoc = (CheckBox) findViewById(R.id.EmailDoc);
		EmailDoc.setTypeface(customFont);
		EmailDoc.setTextSize(18);
	
	      
    /*    ExpandList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
               @Override
               public boolean onChildClick(ExpandableListView arg0,
                       View arg1, int arg2, int arg3, long arg4) {
            	   // to be implemented later
            	   return false;
               }
           });
        
        ExpandList.setOnLongClickListener(new View.OnLongClickListener() {
        	@Override
        	public boolean onLongClick (View v){
        		return false;
        	}
        });  */
		
        leftButton.setOnClickListener(new View.OnClickListener() {
        	
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (ageCounter>0)
					ageCounter--;
				currentAge.setText(ageGroups[ageCounter]);
				currentmilestone = ageID[ageCounter];
				parent.currentmilestone = SummaryPage.currentmilestone;
				
				topLevelGroup = QuestionGroups();
				ExpAdapter = new ExpandListAdapter(SummaryPage.this, topLevelGroup);
				ExpandList.setAdapter(ExpAdapter);
			}
		});
        
        rightButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (ageCounter<ageGroups.length-1)
					ageCounter++;
				currentAge.setText(ageGroups[ageCounter]);
				currentmilestone = ageID[ageCounter];
				parent.currentmilestone = SummaryPage.currentmilestone;
				
				topLevelGroup = QuestionGroups();
				ExpAdapter = new ExpandListAdapter(SummaryPage.this, topLevelGroup);
				ExpandList.setAdapter(ExpAdapter);
			}
		});
        
		emailButton = (Button) findViewById(R.id.email);

		emailButton.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				User curr;
			try{		
				SQLogic c = new SQLogic(SummaryPage.this);
				c.open();
				curr = c.getUserData(SummaryPage.profile_number);
				c.close();  
								
				String age = ageGroups[ageCounter].replaceAll("years", "year").replaceAll("monthes", "month");
				StringBuilder sb = new StringBuilder();
				sb.append("<b>Notes from " + curr.childname + "\'s " + age +" Milestones:</b> <br><br>" );
				sb.append(getNoteChild().get(0).getName());
				String note = sb.toString();
								
				Email_Builder newEmail = new Email_Builder(SummaryPage.this, SummaryPage.profile_number,
						EmailGrid(),note);  
				
				String[] recipients = new String[2];
				recipients[0] = curr.email;
				if(EmailDoc.isChecked()){
					recipients[1] =  curr.docemail;
				}
								
				Email.emailResultsToUser(SummaryPage.this, curr.childname + "\'s " + age + " Act Early Results", 
						newEmail.setSubject(), null, 
						recipients, null, null);
		}
		catch(Exception e){
			e.printStackTrace();
		}
			}
		});  
		
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		this.currentmilestone = parent.currentmilestone;
		ageCounter = IndexOf(SummaryPage.currentmilestone,ageID);
		currentAge.setText(ageGroups[ageCounter]);
		
		//shift dropdown arrow to the RIGHT instead of default LEFT position
		Display tempDisplay= getWindowManager().getDefaultDisplay();
		int width = tempDisplay.getWidth();
		ExpandList.setIndicatorBounds(width-50, width);
		
		// expand list setup code
		try{
	//		topLevelGroup = TopGroup();
			topLevelGroup = QuestionGroups();
			ExpAdapter = new ExpandListAdapter(SummaryPage.this, topLevelGroup);
			ExpandList.setAdapter(ExpAdapter);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
		
	private ArrayList<ExpandListGroup> QuestionGroups(){
		ArrayList<ExpandListGroup> result = new ArrayList<ExpandListGroup>();
		
		ExpandListGroup no = new ExpandListGroup();
		no.setName("No");
		
		ExpandListGroup yes = new ExpandListGroup();
		yes.setName("Yes");
		
		ExpandListGroup maybe = new ExpandListGroup();
		maybe.setName("Not Sure");
		
		ExpandListGroup unanswered = new ExpandListGroup();
		unanswered.setName("Unanswered");
		
		ArrayList<ExpandListChild> no_items = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> yes_items = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> maybe_items = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> unanswered_items = new ArrayList<ExpandListChild>();
		
		ArrayList<QuestionAnswerGroup> QAGroupings = null;
		SQLogic conn = new SQLogic(SummaryPage.this);
		
		try{
			conn.open();
			QAGroupings = conn.GetQuestionAnswerGroup(profile_number, currentmilestone);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			conn.close();
		}
		
		for(int i = 0; i < QAGroupings.size(); i++){
			QuestionAnswerGroup current = QAGroupings.get(i);
			System.out.println(current.getQuestion() + "   " + current.getAnswer());
						
			if(current.getAnswer() == null){
				String temp = current.getQuestion();
				if(current.getUrgency() != 0)  // means its on the urgent list
					temp = "* " + temp;
				
				unanswered_items.add(new ExpandListChild(temp,null));
			}
			
			else if(current.getAnswer().equals(no_ans)){
				String temp = current.getQuestion();
				if(current.getUrgency() != 0)  // means its on the urgent list
					temp = "* " + temp;
				
				no_items.add(new ExpandListChild(temp,null));
			}
			
			else if(current.getAnswer().equals(yes_ans)){
				yes_items.add(new ExpandListChild(current.getQuestion(),null));
			}
						
			else if(current.getAnswer().equals(maybe_ans)){
				String temp = current.getQuestion();
				if(current.getUrgency() != 0)  // means its on the urgent list
					temp = "* " + temp;
				
				maybe_items.add(new ExpandListChild(current.getQuestion(),null));
			}
			
		}
		
		no.setItems(no_items);
		yes.setItems(yes_items);
		maybe.setItems(maybe_items);
		unanswered.setItems(unanswered_items);
		
		ExpandListGroup notes  = new ExpandListGroup();
		notes.setName("Notes");
		notes.setItems(getNoteChild());
		
		result.add(no);
		result.add(yes);
		result.add(maybe);
		result.add(unanswered);
		result.add(notes);
		
		return result;
	}
	
		
	// using this to retrieve note
	private ArrayList<ExpandListChild> getNoteChild(){
		SQLogic conn = new SQLogic(SummaryPage.this);
		JournalObject entry = null;

		try{
			conn.open();
			entry = conn.RetrieveJournalEntry(profile_number);
			conn.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		finally{
			conn.close();
		}
		
		String result;
		if(entry.get(Integer.toString(currentmilestone)) == null)
			result = "";
		else
			result = entry.get(Integer.toString(currentmilestone)).Text;
		
		ExpandListChild temp = new ExpandListChild();
		temp.setName(result);
		
		
		ArrayList<ExpandListChild> n = new ArrayList<ExpandListChild>();
		n.add(temp);
		return n;
	}

	
	// returns index of wanted int
	private int IndexOf(int charac, int[] total){
		for(int i = 0; i < total.length; i++){
			if(total[i] == charac){
				return i;
			}
		}
		return -1;
	}
	
	// equivalent for string
	private int IndexOf(String charac, String[] total){
		for(int i = 0; i < total.length; i++){
			if(total[i].equals(charac)){
				return i;
			}
		}
		return -1;
	}
	
	private String  EmailGrid(){

		StringBuilder sb = new StringBuilder();
		
		SQLogic c = new SQLogic(SummaryPage.this);
		c.open();
		User curr = c.getUserData(profile_number);
		c.close();
		
		String age = ageGroups[ageCounter].replaceAll("years", "year").replaceAll("monthes", "month");
		sb.append("Here is a summary of " + curr.childname + "\'s "  + age + " Milestone Progress: <br><br>");
						

		String yesm = "<b> Milestone Questions Answered Yes to: </b>";
		sb.append(yesm);
		sb.append("<br><br>");
		for(int i = 0; i < topLevelGroup.get(0).getItems().size(); i++){
			String temp = topLevelGroup.get(0).getItems().get(i).getName();
			if(temp.charAt(0) == '*'){
				temp = "<b>" + temp + "</b>";
			}
			sb.append(Integer.toString(i+1) + ". " + temp + "<br>");
			
		}
	
		sb.append("<br><br>");
		sb.append("<b>Milestone Questions Answered No to:</b> <br><br>");
		for(int i = 0; i < topLevelGroup.get(1).getItems().size(); i++){
			String temp = topLevelGroup.get(1).getItems().get(i).getName();
			if(temp.charAt(0) == '*'){
				temp = "<b>" + temp + "</b>";
			}
			sb.append(Integer.toString(i+1) + ". " + temp + "<br>");
		}

		sb.append("<br><br>");
		sb.append("<b>Milestone Questions Answered Not Sure to:</b> <br><br>");
		for(int i = 0; i < topLevelGroup.get(2).getItems().size(); i++){
			String temp = topLevelGroup.get(2).getItems().get(i).getName();
			if(temp.charAt(0) == '*'){
				temp = "<b>" + temp + "</b>";
			}
			sb.append(Integer.toString(i+1) + ". " + temp + "<br>");
		}

		sb.append("<br><br>");
		sb.append("<b>Milestone Questions left Unanswered:</b> <br><br>");
		for(int i = 0; i < topLevelGroup.get(3).getItems().size(); i++){
			String temp = topLevelGroup.get(3).getItems().get(i).getName();
			if(temp.charAt(0) == '*'){
				temp = "<b>" + temp + "</b>";
			}
			sb.append(Integer.toString(i+1) + ". " + temp + "<br>");
		}
		sb.append("<br>");
						
		return sb.toString();
	}
	

/*	private ArrayList<ExpandListGroup> TopGroup(){
		ArrayList<ExpandListGroup> result = new ArrayList<ExpandListGroup>();
		
		ArrayList<ArrayList<ExpandListChild>> children = QuestionChildGroup();
		
		ExpandListGroup no = new ExpandListGroup();
		no.setName("No");
		no.setItems(children.get(1));
		result.add(no);
		
		ExpandListGroup yes = new ExpandListGroup();
		yes.setName("Yes");
		yes.setItems(children.get(0));
		result.add(yes);
						
		ExpandListGroup maybe = new ExpandListGroup();
		maybe.setName("Not Sure");
		maybe.setItems(children.get(2));
		result.add(maybe);
				
		ExpandListGroup unanswered = new ExpandListGroup();
		unanswered.setName("Unanswered");
		unanswered.setItems(children.get(3));
		result.add(unanswered);
		
		ExpandListGroup notes  = new ExpandListGroup();
		notes.setName("Notes");
		notes.setItems(getNoteChild());
		result.add(notes);
				
		return result;
	}
	
	private ArrayList<ArrayList<ExpandListChild>> QuestionChildGroup(){
		SQLogic conn = new SQLogic(SummaryPage.this);
		AnswersObject ans = null;
		QuestionsObject ques = null;
			
		ArrayList<ArrayList<ExpandListChild>> result =	new ArrayList<ArrayList<ExpandListChild>>();
		
		// need to retrieve answered questions
		try{
			conn.open();
			ans = conn.RetrieveAnswers(profile_number);
			ques = conn.RetrieveAllQuestions(currentmilestone, 0);
			System.out.println("}}}}}}}}}}}}}}}}"+ans.getMap().toString());
			conn.close();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		String[] q_keys = new String[ques.count()]; // non-urgent keys in milestone, answer unknown
		ques.getMap().keySet().toArray(q_keys);
		
		String aq_keys[] = new String[ans.count()]; // answers known, but not question or 
		ans.getMap().keySet().toArray(aq_keys); 
		
		// cross reference questions with answers and group in proper array
		ArrayList<ExpandListChild> yes_group = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> no_group = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> maybe_group = new ArrayList<ExpandListChild>();
		ArrayList<ExpandListChild> unanswerd_group = new ArrayList<ExpandListChild>();
		
		for (int i=0; i < q_keys.length; i++)  
		{
			// if q_keys[i] is not found in aq_keys, put question in unanswered list
			int index = IndexOf(q_keys[i],aq_keys);
			if(index == -1){
				unanswerd_group.add(new ExpandListChild(ques.getQuestions(q_keys[i]).Question,null));
			}
			else{
				String a = ans.get(q_keys[i]);
				if(a.equals(yes_ans))
					yes_group.add(new ExpandListChild(ques.getQuestions(q_keys[i]).Question,null));
				else if(a.equals(no_ans))
					no_group.add(new ExpandListChild(ques.getQuestions(q_keys[i]).Question,null));
				else if(a.equals(maybe_ans))
					maybe_group.add(new ExpandListChild(ques.getQuestions(q_keys[i]).Question,null));
			}
			// if found, check answer with key in answersobject ans
			// if yes_ans, put in yes_group, no_ans put in no_group, maybe_ans  put in maybe_group	
		}
		
		result.add(yes_group);
		result.add(no_group);
		result.add(maybe_group);
		result.add(unanswerd_group);
		return result;
	}  */

}





